package com.crape.account.bo.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import magick.MagickException;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import com.crape.account.bo.IImageInfoBO;
import com.crape.account.bo.IUploadBO;
import com.crape.common.constants.ConstantCode;
import com.crape.common.exceptions.BOException;
import com.crape.common.model.ImageInfo;
import com.crape.common.utils.ImageUtil;
import common.Logger;

public class UploadBOImpl implements IUploadBO {
	
	static Logger logger = Logger.getLogger(UploadBOImpl.class);
	
	private IImageInfoBO imageInfoBOImpl;
	
	@Autowired
	public void setImageInfoBOImpl(IImageInfoBO imageInfoBOImpl) {
		this.imageInfoBOImpl = imageInfoBOImpl;
	}

	@Override
	public ImageInfo uploadImage(HttpServletRequest request, MultipartFile fileUpload, String[] imageSize) throws BOException {
		if (fileUpload.isEmpty()) {
			logger.warn("###file not found...");
            throw new BOException("file not found...");
		}
		String fileName = fileUpload.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		if ((ConstantCode.IMAGE_SUFFIX.indexOf(suffix.toUpperCase())<0)) {
			logger.warn("###file format error");
            throw new BOException("file format error");
		}
		logger.info("###uploadImage get file："+fileName);
		ServletContext servletContext = request.getSession().getServletContext();
		try {
			byte[] bytes = fileUpload.getBytes();
			Integer fileSize = (int) fileUpload.getSize() / 1024;
			if (fileSize > 10240) {
	            throw new BOException("file size bigger then 10M...");
			}
			SimpleDateFormat ssss = new SimpleDateFormat("yyyyMMddHHmmssss");
            Date now = Calendar.getInstance().getTime();
            String basePath = servletContext.getRealPath("/");   
            String uploadPath = ConstantCode.uploadPath;
            if (!new File(basePath + uploadPath).isDirectory()) {
                new File(basePath + uploadPath).mkdirs();
            }
            int randomNum = 1000000000 + RandomUtils.nextInt(999999999);
            String fname = ssss.format(now) + "_" + randomNum + suffix.toLowerCase();
			File imageFile = new File(basePath + uploadPath + fname);
			logger.info("file:"+fileName+" save to path:"+basePath + uploadPath + fname);
			FileCopyUtils.copy(bytes, imageFile);
			logger.info("file:"+fileName+" start cut image...");
			List<String> fileList = this.reSizeImage(basePath, uploadPath, fname, imageSize);
			ImageInfo imageInfo = this.getImageInfo(fname, fileList);
			imageInfoBOImpl.insertImageInfo(imageInfo);
            return imageInfo;
		} catch (IOException e) {
			logger.error("IOException" ,e);
            throw new BOException("IOException",e);
		} catch (MagickException e) {
			e.printStackTrace();
			logger.error("MagickException" ,e);
			throw new BOException("MagickException",e);
		} catch (Exception e) {
			logger.error("Exception" ,e);
			throw new BOException("Exception",e);
		} 
	}
	
	private List<String> reSizeImage(String basePath, String uploadPath, String fname, String[] imageSize) throws MagickException{
		List<String> picPathList = new ArrayList<String>();
		String realFromPic = basePath + uploadPath + fname;
		picPathList.add("/"+uploadPath + fname);
		for(String size:imageSize){
			String[] imgSize = size.split("x");
			int width = Integer.valueOf(imgSize[0]);
			int height = Integer.valueOf(imgSize[1]);
			String name = fname.substring(0, fname.lastIndexOf("."));
			String suffix = fname.substring(fname.lastIndexOf("."));
			StringBuilder toPicPath = new StringBuilder();
			toPicPath.append(basePath).append(uploadPath).append(name).append("_").append(size).append(suffix);
			StringBuilder picPath = new StringBuilder();
			picPath.append("/").append(uploadPath).append(name).append("_").append(size).append(suffix);
			logger.info("file:"+fname+" start cut "+ size);
			if(width==height){
				ImageUtil.resetSizeSquare(realFromPic, toPicPath.toString(), width);
			}else{
				ImageUtil.resetSizeRec(realFromPic, toPicPath.toString(), width, height);
			}
			picPathList.add(picPath.toString());
		}
		return picPathList;
	}
	
	private ImageInfo getImageInfo(String fname, List<String> fileList){
		ImageInfo imageInfo = new ImageInfo();
		imageInfo.setName(fname);
		imageInfo.setSuffix(fname.substring(fname.lastIndexOf(".")));
		imageInfo.setUrl(fileList.get(0));
		imageInfo.setUrl1(fileList.get(1));
		imageInfo.setUrl2(fileList.get(2));
		imageInfo.setUrl3(fileList.get(3));
		imageInfo.setUrl4(fileList.get(4));
		imageInfo.setUrl5(fileList.get(5));
		imageInfo.setUrl6(fileList.get(6));
		return imageInfo;
	}

}
